<template>
  <div class="app-container">
    <div class="operation">
      <el-button
        type="primary"
        size="small"
        @click="handleForm(null,null)"
      >
        新增用户
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="userList"
      border
      empty-text="暂无数据"
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        label="姓名"
        align="center"
        width="240"
      >
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        align="center"
        width="240"
      >
      </el-table-column>
      <el-table-column
        prop="email_verified_at"
        label="邮箱验证时间"
        align="center"
        width="240"
      >
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间"
        align="center"
        width="240"
      ></el-table-column>
      <el-table-column
        prop="updated_at"
        label="修改时间"
        align="center"
        width="240"
      ></el-table-column>

      <el-table-column
        align="center"
        label="操作"
        prop="id"
      >
        <template slot-scope="scope">
          <el-button
            type="success"
            size="small"
            @click="changeRole(scope.$index,scope.row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="handleForm(scope.$index,scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <paginAtion
      v-on:getNextPageList='getLoading'
      :paginationMeta="pagination"
    ></paginAtion>

    <!-- New User Or Edit User -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType==='edit'?'编辑用户':'新增用户'"
    >
      <el-form
        :model="userObject"
        label-width="80px"
      >
        <el-form-item label="用户名称">
          <el-input v-model="userObject.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userObject.email"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="userObject.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="userObject.password_confirmation"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align:right">
        <el-button
          type="danger"
          @click="dialogVisible=false"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          @click="confirmUser"
        >
          提交
        </el-button>
      </div>

    </el-dialog>

    <el-dialog
      :visible.sync="dialogRoleVisibile"
      title="分配角色"
    >
      <el-tree
        empty-text="暂无数据"
        :expand-on-click-node="false"
        :data="roleList"
        show-checkbox
        :props="{id:'id',children:'children',label:'display_name'}"
        node-key="id"
        ref="roleTree"
        class="input-tree"
      >
      </el-tree>
      <div class="form-submit operation">
        <el-button
          type="danger"
          @click="dialogRoleVisibile=false"
        >取消</el-button>
        <el-button
          type="primary"
          @click="changeUserRole"
        >提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { getUserList, addUser, deleteUser, changeRoleFromUser } from '@/api/user'
import { getRoleList } from '@/api/role'
import paginAtion from "@/components/Pagination"

export default {
  components: {
    paginAtion
  },
  data() {
    return {
      pagination: {
        current_page: 1,
        from: 1,
        last_page: 1,
        path: '',
        per_page: '10',
        to: 1,
        total: 1
      },
      userList: [],
      loading: true,
      dialogVisible: false,
      dialogType: 'new',
      userObject: {},
      dialogRoleVisibile: false,
      roleList: []
    }
  },
  created() {
    this.init()
    this.getRoleList()
  },
  methods: {
    init() {
      const params = { page: this.pagination.current_page, per_page: this.pagination.per_page }
      getUserList(params)
        .then(
          response => {
            this.loading = false
            if (response.data.length > 0) {
              this.userList = response.data
              this.pagination = response.meta
            }
          }
        )
        .catch(
          error => {
            this.loading = false
            console.log(error)
          }
        )
    },
    getLoading(val) {
      this.pagination.current_page = val
      this.loading = true
      this.init()
    },
    handleForm(index, row) {
      if (row !== null) {
        this.userObject = Object.assign({}, row)
      } else {
        this.userObject = {}
      }
      this.dialogVisible = true
      this.dialogType = 'new'
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该用户，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(
          () => {
            if (row != null) {
              const param = row
              deleteUser(param)
                .then(
                  res => {
                    this.dialogVisible = false
                    this.$message({ message: '操作成功', type: 'success' })
                    this.init()
                  }
                )
                .catch(
                  err => {
                    console.log(err)
                  }
                )
            }
          },
        )
        .catch(() => {

        })
    },
    confirmUser() {
      const param = this.userObject
      addUser(param)
        .then(
          res => {
            console.log(res)
            this.dialogVisible = false
            this.$message({ message: '新增角色成功', type: 'success' })
            this.init()
          }
        )
        .catch(
          err => {
            console.log(err)
            this.dialogVisible = false
            this.$message({ message: '操作失败', type: 'error' })
          }
        )
    },
    changeRole(index, row) {
      const currentCheckNode = []
      this.userObject = row
      this.dialogRoleVisibile = true
      if (row.roles.length > 0) {
        row.roles.forEach(item => {
          currentCheckNode.push(item.id)
        })
      }
      this.$nextTick(() => {
        this.$refs.roleTree.setCheckedKeys(currentCheckNode);//获取已经设置的资源后渲染
      })
    },
    getRoleList() {
      getRoleList({ page: 1, per_page: 1000 })
        .then(
          res => {
            this.roleList = res.data
          }
        )
    },
    /**
     * 修改用户角色
     */
    changeUserRole() {
      const checkNodes = this.$refs.roleTree.getCheckedKeys();
      const data = { role_id: checkNodes }
      var that = this
      changeRoleFromUser(this.userObject.id, data)
        .then(
          res => {
            this.dialogRoleVisibile = false
            this.$message({ message: '操作成功', type: 'success' })
            that.init()
          }
        )
        .catch(
          err => {
            console.log(err)
          }
        )
    }
  }
}
</script>

<style scoped>
.operation {
  padding: 10px 0;
}
</style>